/*
 * UserSessionList.java
 *
 * Created on 28 de Junho de 2005, 23:45
 */

package jhub;
import java.io.IOException;
import java.util.*;
import jhub.users.Admin;
import jhub.users.Operator;
import jhub.users.User;
/**
 *
 * @author  botelhodaniel
 */
public class UserSessionList /*extends Hashtable<String,UserSession>*/{
    private Hashtable<String, UserSession> userlist;
    
    /**
     * Creates a new instance of UserSessionList
     */
    public UserSessionList() {
        userlist = new Hashtable<String,UserSession>();
    }
    
    public String getNickList(){
        StringBuffer nicklist = new StringBuffer("$NickList ");
        
        Enumeration<UserSession> users = userlist.elements();
        
        while(users.hasMoreElements())
            nicklist.append(users.nextElement().getUser().getNick() + "$$");
        
        return nicklist.append('|').toString()+"";
    }
    
    public String getOpList(){
        StringBuffer nicklist = new StringBuffer("$OpList ");
        
        Enumeration<UserSession> users = userlist.elements();
        
        while(users.hasMoreElements()){
            User user = users.nextElement().getUser();

            if(user instanceof Operator ){
                nicklist.append(user.getNick() + "$$");
            }
        }
            
        
        return nicklist.append('|').toString();
    }
    
    public synchronized void addUser(UserSession user){
        System.out.println("New User: "+user.getUser().getNick());
        userlist.put(user.getUser().getNick(),user);
    }
    
    public UserSession getUser(String nick){
        return userlist.get(nick);
    }
    
    public void removeAll() {
        for(UserSession channel : userlist.values())
            removeUser(channel);
    }
    
    
    public void removeUser(UserSession user) {
        try {
            
            user.close();
            user.setEnd(new Date());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        userlist.remove(user.getUser().getNick());
    }
    
    public Enumeration<UserSession> elements() {
        return userlist.elements();
    }

    public boolean contains(String string) {
        return userlist.containsKey(string);
    }
    
}
